import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cupertino_date_picker_fork/flutter_cupertino_date_picker_fork.dart';
import 'package:ls_work/a_yyt/models/visit_entity.dart';
import 'package:ls_work/a_yyt/widget/visit_record_cell.dart';
import 'package:ls_work/common/common.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/res/gaps.dart';
import 'package:ls_work/res/styles.dart';
import 'package:ls_work/util/event_bus.dart';
import 'package:ls_work/util/toast.dart';
import 'package:ls_work/widgets/click_item.dart';
import 'package:ls_work/widgets/my_refresh_list.dart';
import 'package:date_format/date_format.dart';

import '../../util/flat_button.dart';



class HumanVisitUnConfirmPage extends StatefulWidget {
  @override
  _HumanVisitUnConfirmPageState createState() =>
      _HumanVisitUnConfirmPageState();
}

class _HumanVisitUnConfirmPageState extends State<HumanVisitUnConfirmPage>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  TextEditingController textViewController = TextEditingController();
  List<VisitInfo> dataList = [];
  bool isMore = false;
  int _page = 1;
  String _keyWord = '';
  String _confirmTime = '';
  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _fectData();
    });
    eventBus.on(Constant.eventHumanVisitSeaarch, (arg) {
      List target = arg;
      if (target.last == 0) {
        _keyWord = target.first;
        _onRefresh();
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return DeerListView(
      key: Key('_list'),
      itemCount: dataList.length,
      onRefresh: _onRefresh,
      loadMore: _loadMore,
      hasMore: isMore,
      itemBuilder: (_, index) {
        return Container(
          padding: EdgeInsets.only(top: 12),
          child: VisitRecordCell(
            onTap: () {
              _bottomConfirmButtonSheetAlert(dataList[index]);
            },
            info: dataList[index],
          ),
        );
      },
    );
  }

  _fectData() {
    SVProgressHUD page = SVProgressHUD(context);
    var map = {
      'page': _page,
      'rows': 20,
      'validStatus': 0,
      'preNameLike': _keyWord,
      'sourceId': 2
    };
    print(map);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post('${HttpApi.visitRecordList}?${requestParams(map)}')
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            VisitListModel model = VisitListModel.fromJson(map['data']);
            if ((model.rows??[]).length > 0) {
              isMore = (model.rows??[]).length == 20;
              setState(() {
                if (_page == 1) {
                  /// 刷新
                  dataList.clear();
                  dataList.addAll(model.rows??[]);
                } else {
                  dataList.addAll(model.rows??[]);
                }
              });
            } else {
              if (_page == 1) {
                /// 刷新
                setState(() {
                  dataList.clear();
                  dataList.addAll(model.rows??[]);
                });
              }
              Toast.show("没有更多数据");
            }
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  Future _onRefresh() async {
    _page = 1;
    await _fectData();
  }

  Future _loadMore() async {
    _page++;
    await _fectData();
  }

  _visitConfirm({int? id}) {
    if (TextUtil.isEmpty(_confirmTime)) {
      Toast.show('请选择接待时间');
      return;
    }
    if (TextUtil.isEmpty(textViewController.text)) {
      Toast.show('请输入接待描述');
      return;
    }
    SVProgressHUD page = SVProgressHUD(context);
    var map = {
      'id': id,
      'confirmTime': _confirmTime,
      'confirmRemark': textViewController.text
    };
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post('${HttpApi.visitRecordConfirm}?${requestParams(map)}')
        .then((r) {
      ///
      page.closeProgress();
      Navigator.pop(context);
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          Toast.show(map["msg"]);
          _confirmTime = '';
          _onRefresh();
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  ///调起时间选择器
  void _showDateTimePicker(VoidCallback callBack) {
    DatePicker.showDatePicker(
      context,
      minDateTime: DateTime.now(),
      maxDateTime: DateTime.parse("2099-01-01 00:00:00"),
      initialDateTime: DateTime.parse(formatDate(DateTime.now(),
          [yyyy, "-", mm, "-", "dd", " ", HH, ":", nn, ":", ss])),
      dateFormat: "yy年M月d日    EEE,H时:m分",
      locale: DateTimePickerLocale.zh_cn,
      pickerTheme: DateTimePickerTheme(
        showTitle: true,
        // title: Text('$customerName'),
        confirm: Text('确定'),
      ),
      pickerMode: DateTimePickerMode.datetime,
      onConfirm: (dateTime, List<int> index) {
        _confirmTime =
            DateUtil.formatDate(dateTime, format: 'yyyy-MM-dd HH:mm:ss');
        callBack();
      },
    );
  }

  ///确认接单弹窗
  _bottomConfirmButtonSheetAlert(VisitInfo info) {
    showModalBottomSheet(
      backgroundColor: Colors.white,
      context: context,
      isScrollControlled: true,
      isDismissible: true,
      builder: (BuildContext context) {
        return StatefulBuilder(
          builder: (context, setDialogState) {
            return Container(
              height: ScreenUtil.getScreenH(context) * 2 / 3 +
                  ScreenUtil.getScaleH(context, 70),
              color: Colors.white,
              child: Column(
                children: <Widget>[
                  Gaps.vGap50,
                  Text(
                    '${info.customerName}',
                    style: TextStyle(fontSize: 20, color: Colours.text_dark),
                  ),
                  Gaps.vGap15,
                  ClickItem(
                    title: '选择接待时间',
                    titleStyle: TextStyles.textDark16,
                    content: _confirmTime,
                    onTap: () {
                      _showDateTimePicker(() {
                        setDialogState(() {
                          _confirmTime = _confirmTime;
                        });
                      });
                    },
                  ),
                  Gaps.vGap15,
                  Container(
                    padding: EdgeInsets.all(20),
                    color: Colors.white,
                    alignment: Alignment.topLeft,
                    height: 200,
                    child: TextField(
                      controller: textViewController,
                      maxLines: 10,
                      maxLength: 300,
                      autofocus: false,
                      decoration: InputDecoration(
                        hintText: "请输入接待描述",
                        hintMaxLines: 20,
                        fillColor: Colours.bg_color,
                        filled: true,
                        border: InputBorder.none,
                      ),
                    ),
                  ),
                  // Gaps.vGap50,
                  Container(
                    padding: EdgeInsets.all(30),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: <Widget>[
                        FlatsButton(
                          color: Colours.text_gray,
                          onPressed: () {
                            Navigator.pop(context);
                          },
                          child: Text(
                            '取消',
                            style: TextStyle(color: Colours.text_dark),
                          ),
                        ),
                        FlatsButton(
                          color: Colors.blue[300]!,
                          onPressed: () {
                            _visitConfirm(id: info.id);
                          },
                          child: Text(
                            '确定',
                            style: TextStyle(color: Colors.white),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            );
          },
        );
      },
    );
  }
}
